package com.yl.immodule.widget;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.yl.immodule.R;
import com.yl.immodule.v.models.ChatMessageViewModel;
import com.unionbroad.greendao.ChatMessage;
import com.unionbroad.app.util.Logger;

import java.util.ArrayList;
import java.util.List;

public class ChatMessageViewAdapter extends RecyclerView.Adapter<BaseChatMessageViewHolder> {

    public interface OnItemResendClickListener {
        void onItemResendClick(View item, int position);
    }

    private static final int TYPE_LEFT = 1;
    private static final int TYPE_RIGHT = 2;

    private Logger mLogger = Logger.getLogger("ChatMessageViewAdapter");
    private final ArrayList<ChatMessage> mMessageList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private LayoutInflater mLayoutInflater;
    private AdapterView.OnItemClickListener mOnItemClickListener;
    private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
    private OnItemResendClickListener mOnItemResendClickListener;
    private ChatMessageViewModel mViewModel;

    public ChatMessageViewAdapter(Context context, RecyclerView recyclerView, ChatMessageViewModel viewModel, LifecycleOwner lifecycleOwner) {
        mLayoutInflater = LayoutInflater.from(context.getApplicationContext());
        mRecyclerView = recyclerView;
        mViewModel = viewModel;
        
        // 观察消息列表变化
        mViewModel.messageList.observe(lifecycleOwner, messages -> {
            mMessageList.clear();
            if (messages != null) {
                mMessageList.addAll(messages);
            }
            notifyDataSetChanged();
        });
        
        // 观察新消息添加
        mViewModel.newMessage.observe(lifecycleOwner, message -> {
            if (message != null) {
                int position = -1;
                for (int i = 0; i < mMessageList.size(); i++) {
                    if (mMessageList.get(i).getId().equals(message.getId())) {
                        position = i;
                        break;
                    }
                }
                if (position != -1) {
                    notifyItemChanged(position);
                }
            }
        });
        
        // 观察滚动位置变化
        mViewModel.scrollPosition.observe(lifecycleOwner, position -> {
            if (position != null && position >= 0 && position < mMessageList.size()) {
                mRecyclerView.smoothScrollToPosition(position);
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        if (position >= 0 && position < getItemCount()) {
            ChatMessage message = mMessageList.get(position);
            return message.getIs_out() ? TYPE_RIGHT : TYPE_LEFT;
        }
        return -1;
    }

    @Override
    public BaseChatMessageViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        mLogger.d("onCreateViewHolder viewType=" + viewType);
        switch (viewType) {
            case TYPE_LEFT:
                return new ChatMessageViewHolder(mLayoutInflater.inflate(R.layout.chat_left_message_layout, null), mViewModel.getChatId(), mViewModel);
            case TYPE_RIGHT:
                return new ChatMessageViewHolder(mLayoutInflater.inflate(R.layout.chat_right_message_layout, null), mViewModel.getChatId(), mViewModel);
        }
        return new EmptyHolder(new View(mLayoutInflater.getContext()));
    }

    @Override
    public void onBindViewHolder(final BaseChatMessageViewHolder viewHolder, int position) {
        if (position >= 0 && position < getItemCount()) {
            viewHolder.position = viewHolder.getAdapterPosition();
            
            // 设置adapter引用
            if (viewHolder instanceof ChatMessageViewHolder) {
                ((ChatMessageViewHolder) viewHolder).setAdapter(this);
            }
            
            boolean needTimeDivision;
            final ChatMessage message = mMessageList.get(position);
            if (position == 0) {
                needTimeDivision = true;
            } else {
                long timeDiff = message.getTime_stamp() - mMessageList.get(position - 1).getTime_stamp();
                needTimeDivision = timeDiff > 200000;
            }
            viewHolder.bindViewData(message, needTimeDivision);

            viewHolder.setOnClickListener(v -> {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(null, v, viewHolder.position, v.getId());
                }
            });
            
            viewHolder.setOnLongClickListener(v -> {
                if (mOnItemLongClickListener != null) {
                    mOnItemLongClickListener.onItemLongClick(null, v, viewHolder.position, v.getId());
                }
                return false;
            });
            
            viewHolder.setOnResendEventListener(v -> {
                if (mOnItemResendClickListener != null) {
                    mOnItemResendClickListener.onItemResendClick(viewHolder.itemView, viewHolder.position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mMessageList.size();
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
        mOnItemClickListener = l;
    }

    public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener l) {
        mOnItemLongClickListener = l;
    }

    public void setOnItemResendClickListener(OnItemResendClickListener l) {
        mOnItemResendClickListener = l;
    }

    public ChatMessage getDataByPosition(int position) {
        if (position < mMessageList.size()) {
            return mMessageList.get(position);
        }
        return null;
    }

    public ArrayList<ChatMessage> getData() {
        return mMessageList;
    }

    public int getLastPosition() {
        if (getItemCount() > 0) {
            return getItemCount() - 1;
        } else {
            return 0;
        }
    }

    public void updateItemData(ChatMessage message) {
        // 由于ViewModel的updateMessage方法是private的，需要改用公有方法
        // 目前可以简单地直接更新本地数据，因为ViewModel会通过观察自动更新UI
        for (ChatMessage chatMessage : mMessageList) {
            if (message.getId().equals(chatMessage.getId())) {
                chatMessage.setLocalFile(message.getLocalFile());
                break;
            }
        }
    }

    public void updateItem(ChatMessage chatMessage) {
        // 目前可以简单地直接更新本地数据
        boolean hasUpdated = false;
        int count = mRecyclerView.getChildCount();
        for (int i = 0; i < count; i++) {
            BaseChatMessageViewHolder holder = (BaseChatMessageViewHolder) mRecyclerView.getChildViewHolder(mRecyclerView.getChildAt(i));
            if (holder.position > mMessageList.size() -1) {
                continue;
            }
            ChatMessage hitMessage = mMessageList.get(holder.position);
            if (chatMessage.getId().equals(hitMessage.getId())) {
                hitMessage.setSip_status(chatMessage.getSip_status());
                hitMessage.setDuration(chatMessage.getDuration());
                hitMessage.setUpdown_progress(chatMessage.getUpdown_progress());
                notifyItemChanged(holder.position);
                hasUpdated = true;
                break;
            }
        }
        if (!hasUpdated) {
            for (ChatMessage message : mMessageList) {
                if (message.getId().equals(chatMessage.getId())) {
                    message.setSip_status(chatMessage.getSip_status());
                    break;
                }
            }
        }
    }

    public void updateAll(ArrayList<ChatMessage> messages) {
        // 使用ViewModel更新所有消息
        if (mViewModel != null) {
            mViewModel.loadMessages();
        }
    }

    public void addChatMessage(ChatMessage message) {
        // 使用ViewModel添加消息
        if (mViewModel != null) {
            try {
                // 由于ViewModel的addMessage方法是private的，需要使用sendMessage代替
                mViewModel.sendMessage(message);
            } catch (Exception e) {
                mLogger.e("添加消息失败: " + e.getMessage());
            }
        }
    }

    public void addChatMessage(List<ChatMessage> messages) {
        // 由于ViewModel的addMessages方法是private的，这里暂时无法直接使用
        // 可以一个一个添加
        if (mViewModel != null && messages != null) {
            for (ChatMessage message : messages) {
                try {
                    mViewModel.sendMessage(message);
                } catch (Exception e) {
                    mLogger.e("添加消息列表失败: " + e.getMessage());
                }
            }
        }
    }

    public void removeChatMessage(int position) {
        if (position >= 0 && position < mMessageList.size()) {
            // 使用ViewModel删除消息
            ChatMessage message = mMessageList.get(position);
            if (mViewModel != null) {
                try {
                    mViewModel.deleteMessage(message);
                } catch (Exception e) {
                    mLogger.e("删除消息失败: " + e.getMessage());
                    // 如果失败，直接从本地列表中移除
                    mMessageList.remove(position);
                    notifyItemRemoved(position);
                }
            } else {
                // 如果ViewModel为空，直接从本地列表中移除
                mMessageList.remove(position);
                notifyItemRemoved(position);
            }
        }
    }

    public void clearAll() {
        // 清空本地列表
        mMessageList.clear();
        notifyDataSetChanged();
    }
}
